package controllers

import (
	"app/config"
	"app/daos"
	. "app/utils"
	"github.com/fwhezfwhez/errorx"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type User struct {
	Dashboard
}

// Login 1 user/login 登录
func (user *User) Login(c *gin.Context) gin.H {
	params, err := GetStructByParams[UserLogin](c)
	if err != nil {
		return user.WarnResponse(1, err.Error())
	}

	var userModel = daos.Admin{Username: params.Username, Enabled: 1}
	if err = daos.GetConnection().Debug().Where(&userModel).First(&userModel).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return user.WarnResponse(2, "用户不存在或已禁用")
		}

		return user.ErrResponse(2, errorx.MustWrap(err))
	}

	if err = PasswordCheck(params.Password, userModel.Password); err != nil {
		return user.WarnResponse(3, "密码错误")
	}

	//若用户在另一台机器上已登录则将该账号session销毁
	sessionIds := SessionMagage.GetSessionIDList()
	for _, k := range sessionIds {
		if SessionMagage.GetSessionVal(k, "id") == userModel.ID {
			SessionMagage.SessionEnd(k)
		}
	}

	//查询用户角色信息
	var userRole []daos.AdminRole
	if err = daos.GetConnection().Where("admin_id = ?", userModel.ID).Find(&userRole).Error; err != nil {
		return user.WarnResponse(4, err.Error())
	}

	var permissionList []float64
	var menuList []float64
	if userModel.IsAdmin == 1 { //管理员所有权限菜单游戏
		for _, v := range config.Cfg.Permission {
			permissionList = append(permissionList, v["id"].(float64))
		}

		for _, v := range config.Cfg.Menu {
			menuList = append(menuList, v["id"].(float64))
		}
	} else if len(userRole) != 0 { //非管理员且有角色
		var roleId []int
		for _, v := range userRole {
			roleId = append(roleId, v.RoleId)
		}

		//查询角色权限
		var rolePermission []daos.RolePermission
		if err = daos.GetConnection().Where("role_id in ?", roleId).Find(&rolePermission).Error; err != nil {
			return user.WarnResponse(3, err.Error())
		}

		for _, v := range rolePermission {
			if v.PermissionId != 0 {
				permissionList = append(permissionList, float64(v.PermissionId))
			}

			if v.MenuId != 0 {
				menuList = append(menuList, float64(v.MenuId))
			}
		}
	}

	//新建session
	sessionId := SessionMagage.SessionStart("")
	SessionMagage.SetSessionVal(sessionId, "id", userModel.ID)
	SessionMagage.SetSessionVal(sessionId, "username", userModel.Username)
	SessionMagage.SetSessionVal(sessionId, "nickname", userModel.Nickname)
	SessionMagage.SetSessionVal(sessionId, "isAdmin", userModel.IsAdmin)
	return user.Response(gin.H{"userId": userModel.ID, "sessionId": sessionId, "nickname": userModel.Nickname,
		"isAdmin": userModel.IsAdmin, "menu": Float64s2Str(menuList), "permission": Float64s2Str(permissionList)})
}

// ChangePassword 2 user/changePassword 修改密码
func (user *User) ChangePassword(c *gin.Context) gin.H {
	params, err := GetStructByParams[UserChangePassword](c)
	if err != nil {
		return user.WarnResponse(1, err.Error())
	}

	if params.NewPassword != params.ConfirmPassword {
		return user.WarnResponse(2, "密码不一致")
	}

	password := HashPassword(params.NewPassword)

	daos.GetConnection().Model(&daos.Admin{}).Where("id = ? ", params.UserId).Update("password", password)
	SessionMagage.SessionEnd(c.GetHeader("SESSION-ID"))
	return user.Response(gin.H{})

}

// Logout 3 user/logout 登出
func (user *User) Logout(c *gin.Context) gin.H {
	SessionMagage.SessionEnd(c.GetHeader("SESSION-ID"))
	return user.Response(gin.H{})
}
